package com.d3works.studio.db.repo;

import com.d3works.inject.Beans;
import com.d3works.meta.db.MetaJsonField;
import com.d3works.meta.db.MetaModel;
import com.d3works.meta.db.repo.MetaJsonFieldRepository;
import com.d3works.meta.db.repo.MetaModelRepository;
import com.d3works.studio.db.AppBuilder;
import com.d3works.studio.service.JsonFieldService;
import com.d3works.studio.service.StudioMetaService;
import com.google.inject.Inject;

public class MetaJsonFieldRepo extends MetaJsonFieldRepository {

  @Inject MetaModelRepository metaModelRepo;

  @Override
  public MetaJsonField save(MetaJsonField metaJsonField) {

    AppBuilder appBuilder = metaJsonField.getAppBuilder();
    if (appBuilder != null) {
      metaJsonField.setIncludeIf("__config__.app.isApp('" + appBuilder.getCode() + "')");
    }

    Beans.get(JsonFieldService.class).updateSelection(metaJsonField);

    return super.save(metaJsonField);
  }

  @Override
  public void remove(MetaJsonField metaJsonField) {

    if (metaJsonField.getJsonModel() == null) {

      MetaModel metaModel =
          metaModelRepo.all().filter("self.fullName = ?1", metaJsonField.getModel()).fetchOne();

      Beans.get(StudioMetaService.class)
          .trackingFields(metaModel, metaJsonField.getName(), "Field removed");
    }

    Beans.get(JsonFieldService.class).removeSelection(metaJsonField);

    super.remove(metaJsonField);
  }
}
